var appPath = getAppPath();
var EDIT_IMG_IDX = 0;

$(function(){

	// 合作方(检索用)
	$("#queryPartner").combobox({
		url:appPath+'/itbOrders/getPartnerForCombo.action?blkFlg=1',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdM){
			// TODO
		}
	});
	
	// 合作方(更新用)
	$("#updPartner").combobox({
		url:appPath+'/itbOrders/getPartnerForCombo.action',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdM){
			// TODO
		}
	});
	
	
	$("#expType").combobox({//初始化物流公司分类
		url:appPath + "/itbOrders/getExpClassificationInfo.action",
		valueField : 'exc_id',
		textField : 'name',
		onLoadSuccess:function(){
			$("#expType").combobox('select',0).combobox('enable');
		},
		onSelect:function(selRecdM){
			var text = $("#expType").combobox('getText');
			$("#editExpress").val(text);
		}
	});
	
	initOrdersGrid();
	initDetailGrid();
});

function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    var h = dt.getHours();
    var mm = dt.getMinutes();
    var s = dt.getSeconds();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d)+' '+(h<10?('0'+h):h)+':'+(mm<10?('0'+mm):mm)+':'+(s<10?('0'+s):s);
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 订单列表初始化
function initOrdersGrid(){
	
	$('#ordersGrid').datagrid({
	    url:appPath + "/itbOrders/getOrdersInfoPg.action",
	    height:'full',
	    //remoteSort:false,
	    nowrap: false,// 换行
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'order_id',title:'订单ID',width:35,align:'center',sortable:false,
  	        	formatter:function(value,rowData,rowIndex){
  	        		if (rowData.vipOrd) return value;
  	        		return value+'<div id="ord_'+value+'"><i class="fa fa-meh-o"></i>';
  	        	}
  	        },
  	        {field:'order_no',title:'订单号',width:68,align:'center',sortable:false,
  	        	formatter:function(value,rowData,rowIndex){
  	        		return "N:"+value+'<br/>P:'+rowData.pay_order_no;
  	        	}
  	        },
//  	        {field:'pay_order_no',title:'支付订单号',width:50,align:'center',sortable:false,
//		    	  formatter:function(value, rowData, rowIndex){
//		    		  return '<span style="color:red;">'+value+'</span>';
//		    	  }
//		      },
  	        {field:'type',title:'订单类型',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  	var show = '未知';
		    		  	if (rowData.vipOrd) return '<font color="red">VIP</font>';
	  	        		switch(Number(value||'0')){
  	        				case 0: {
  	        					show='<span style="color:black">普通</span>';
  	        					if(rowData.parentOrderType==10) {
  	        						show+='</br><span style="color:green">(拆)</span>';
  	        					}else if(rowData.parentOrderType==20) {
  	        						show+='</br><span style="color:red">(秒)</span>';
  	        					}
  	        				}
  	        				break;
	  	        			case 10: show='<span style="color:green">被拆分</span>'; break;
	  	        			case 20: show='<span style="color:red">秒杀</span>'; break;
	  	        		}
	  	        		
	  	        		return show
		    	  }
		      },
//		    {field:'downInfo',title:'导出订单',width:40,align:'center',sortable:false,
//  	        	formatter:function(value, rowData, rowIndex){
//  	        		if(!rowData.order_id) return "N/A";
//  	        		if (rowData.vipOrd) return "<a href='javascript:void(0)' onClick='downOrderInfo(0,1)'>导出</a>";
//  	        		return "<a href='javascript:void(0)' onClick='downOpen()'>导出</a>"
////  	        		return "<a href='javascript:void(0)' style='color:red' onClick='downOrderInfo("+rowData.order_id+",0,0)'>正常血</a>"+
////  	        			"</br><a href='javascript:void(0)' style='color:red;' onClick='downOrderInfo("+rowData.order_id+",1,0)'>高精血</a>"+
////  	        			"</br><a href='javascript:void(0)' onClick='downOrderInfo("+rowData.order_id+",0,1)'>正常</a>"+
////  	        			"</br><a href='javascript:void(0)' onClick='downOrderInfo("+rowData.order_id+",1,1)'>高精</a>";
//	        	}
//		    },
  	        {field:'user_id',title:'用户ID',width:35,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if (rowData.user_delFlg == 1) {
		    			return '<font color="red">'+value+'</font>';
		    		}
		    		if (value) {
		    			return '<a href="javascript:void(0)" onclick="sendCoupon('+value+')">'+value+'</a>';
		    		}
		    		return '';
		    	}
  	        },
  	        {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
		    {field:'downInfo2',title:'用户文档',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
  	        		if (rowData.vipOrd) return "N/A";
  	        		return "<a href='javascript:void(0)' onClick='downOdrUserDocInfo("+rowData.order_id+")'>导出</a>";
	        	}
		    },
	        {field:'detail_cnt',title:'订单明细',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return "N/A";
	        		var show = '共<span style="color:red">['+(value||'0')+']</span>件';
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.order_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
	        		var show = getState4Show(value);
	        		if(value==40||value==50) {
	        			return show;
	        		} else {
	        			return "<a href='javascript:void(0)' onClick='editState("+rowData.order_id+")'>"+show+"</a>";
	        		}
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:30,align:'center',sortable:false},
  	        {field:'partner_name',title:'合作方',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pnm = '<span style="color:red;">未设定</span>';
  	        		if(value && value.length>0) {
  	        			pnm = value;
  	        		}
	        		return "<a href='javascript:void(0)' onClick='editPartner("+
	        			rowData.order_id+","+
	        			"\""+rowData.order_no+"\","+
	        			rowData.partner_id+")'>"+
	        			pnm+"</a>";
	        	}
		    },
  	        {field:'pay_platform',title:'支付平台',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pf = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: pf="微信"; break;
  	        			case 20: pf="支付宝"; break;
  	        			case 30: pf="苹果内购"; break;
  	        		}
  	        		return pf;
	        	}
		    },
	        {field:'total_fee',title:'订单金额',width:45,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id) return "N/A";
		    		  var show = Number(value||'0')/100;
		    		  return '<span style="color:red;">'+show+'</span>元';
		    	  }
		      },
		    {field:'coupon_id',title:'券ID',width:35,align:'center',sortable:false},
		    {field:'coupon_fee',title:'优惠金额',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id || !rowData.coupon_id) return "";
		    		  var show = Number(value||'0')/100;
		    		  if(show>0) {
		    			  show = '<span style="color:green;">'+show+'</span>';
		    		  }
		    		  return show+'元';
		    	  }
		      },
		    {field:'express_type',title:'运费',width:30,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var mt = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: mt='<span style="color:green">已付</span>'; break;
  	        			case 20: mt='<span style="color:red">到付</span>'; break;
  	        		}
  	        		return mt;
	        	}
		    },
	        {field:'addr_name',title:'收件人',width:30,align:'center',sortable:false},
		    {field:'addr_id',title:'收件地址',width:50,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
	        		return (rowData.addr_city||'') + ' '+ (rowData.addr_detail||'');
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:50,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'<i class="fa fa-download" style="color:red;">导出订单</i>',
				handler:function(){
					downOrdOpen();// 正常订单
				}
			},
//			'-',
//			{
//				text:'<i class="fa fa-download"></i>导出高精度订单',
//				handler:function(){
//					downOrderInfo(1,1);// 导出高精度订单
//				}
//			},
//			'-',
//			{
//				text:'<i class="fa fa-download" style="color:red;"></i>正常2mm血',
//				handler:function(){
//					downOrderInfo(0,-1);// 正常2mm血
//				}
//			},
//			'-',
//			{
//				text:'<i class="fa fa-download" style="color:red;"></i>正常2mm血',
//				handler:function(){
//					downOrderInfo(1,-1);// 正常2mm血
//				}
//			},
//			'-',
//			{
//				text:'<i class="fa fa-download" style="color:green;"></i>正常3mm血',
//				handler:function(){
//					downOrderInfo(0,0);// 正常订单
//				}
//			},
//			'-',
//			{
//				text:'<i class="fa fa-download" style="color:green;"></i>高精度3mm血',
//				handler:function(){
//					downOrderInfo(1,0);// 正常订单
//				}
//			},
			'-',
			{
				text:'<i class="fa fa-refresh"></i>重置时间',
				handler:function(){
					clearTime();
				}
			},
			'-',
			{
				text:'批量导出订单',
				iconCls:'icon-save',
				handler:function(){
					exportAlls();
				}
			},
			'-',
			{
				text:'<i class="fa fa-eye" style="color:red;font-size:14px"></i>检查订单',
				handler:function(){
					chkOrdValid();// 检测订单有效性
				}
			}
		]
	});
}

function downOrdOpen(){
	$('#downOrdDiv').window({
		title: '导出订单',
		iconCls:'icon-save',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#downOrdDiv').window('move',{top:0,left:200});
	$('#downOrdDiv').window('open');
}

// <i class="fa fa-warning" style="font-size:24px"></i>
// <i class="fa fa-thumbs-o-up" style="font-size:24px"></i>
// <i class="fa fa-spinner" style="font-size:24px"></i> 待检测

// 检查订单有效
function chkOrdValid(){
	var selectItem = $("#ordersGrid").datagrid('getChecked');// 选中的订单
	if (!selectItem || selectItem.length == 0){
		return $.messager.alert('提示信息','请选择需要检查的订单','warning');
	}
	

	var arr = [];
	var ids = '';
	$.each(selectItem,function(indx,item){
		arr.push(item.order_id);
		ids = ids + item.order_id +','
	});
	
	var parm = "["+ids.substring(0, ids.length-1)+"]";
	console.log(parm);
	
	$.messager.confirm('提示框消息','<font color="blue">是否确定检查该订单?</font>',function(r){
		if (r){
			$.loading(true);
			var url = getApiServer() + "/yjsc/v2/api4back/checkOrderDocuments";
			$.ajax({
				url:url,  //请求的URL
				timeout : 30000, //超时时间设置，单位毫秒
				type : 'get',  //请求方式，get或post
				data :{'orderIds' : parm},  //请求所传参数，json格式
				dataType:'json',//返回的数据格式
				success:function(ret){ //请求成功的回调函数
					if (ret.success == 1) {
						var info = [];// 错误信息
						var da = ret.data;
						for(var i=0;i<arr.length;i++){
							var orId = arr[i];
							var re = 0;
							var json = da[orId];
						    for(var ky in json){
						        re += json[ky].result;
						        
						        if (json[ky].result == 1){
						        	var d = {};
						        	 d[ky] = json[ky];
						        	info.push(d);
						        }
						    }
						    console.log(re);
							if (re>0) { // 表示有错误
								$("#ord_"+orId+"").html('<i class="fa fa-warning" style="color:red;font-size:14px"></i>');
							} else {
								$("#ord_"+orId+"").html('<i class="fa fa-thumbs-o-up" style="color:green;font-size:14px"></i>');
							}
						}
						console.log(info);
						if (info.length>0 && JSON.stringify(info)){
							var htm = '<textarea rows="10" cols="30">'+JSON.stringify(info)+'</textarea>';
							$.messager.alert('提示信息',htm);
						}
						$.loading(false);
					} else {
						$.loading(false);
						$.messager.alert('提示信息','请求出错,请选择正确的印刷订单!','warning');
					}
				},
				complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
					if(status=='timeout'){//超时,status还有success,error等值的情况
				 　　		$.loading(false);
				　　}
				}
			});
			
			
//			$.post(url,function(ret){
//				if (ret.success == 1){
//					var da = ret.data;
//					for(var i=0;i<arr.length;i++){
//						var orId = arr[i];
//						var re = 0;
//						var json = da[orId];
//					    for(var ky in json){
//					        re += json[ky].result;
//					    }
//					    console.log(re);
//						if (re>0){ // 表示有错误
//							$("#ord_"+orId+"").html('<i class="fa fa-warning" style="color:red;font-size:14px"></i>');
//						} else {
//							$("#ord_"+orId+"").html('<i class="fa fa-thumbs-o-up" style="color:green;font-size:14px"></i>');
//						}
//					}
//					$.loading(false);
//				} else {
//					$.loading(false);
//					$.messager.alert('提示信息','请求失败!','warning');
//				}
//			});
			
		}
	});
	
	
	
	
	
	
	
	
}

function sendCoupon(userId){
	$("#couponForm").form('clear');
	$("#couponUserId").html(userId);
	$("#hiCouponUserId").val(userId);
	$('#coupon').window({
		title: '指定优惠券列表',
		iconCls:'icon-save',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#coupon').window('move',{top:20,left:20});
	$('#coupon').window('open');
	initCoupon();
}

// 被导出的订单列表
function initExOrderGrid(){
	var allOrderId='';
	$('#exOrderGrid').datagrid({
	    url:appPath + "/itbOrders/getOrdersInfoPg.action?page=1&&rows=1000",
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    fit:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    AllowPaging :false,
	    columns:[[
  	        {field:'order_id',title:'订单ID',width:25,align:'center',sortable:false,
  	        	formatter:function(value, rowData,rowIndex){
  	        		allOrderId += value +",";
  	        		$("#allIds").val(allOrderId);
  	        		return value;
  	        	}
  	        },
  	        {field:'order_no',title:'订单号',width:50,align:'center',sortable:false},
  	        {field:'pay_order_no',title:'支付订单号',width:50,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red;">'+value+'</span>';
		    	  }
		      },
  	        {field:'user_id',title:'用户ID',width:30,align:'center',sortable:false},
  	        {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
	        {field:'detail_cnt',title:'订单明细',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return "N/A";
	        		var show = '[点击查看] '+(value||'0')+'件';
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.order_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
	        		var show = getState4Show(value);
	        		if(value==40||value==50) {
	        			return show;
	        		} else {
	        			return show;
	        		}
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:27,align:'center',sortable:false},
  	        {field:'partner_name',title:'合作方',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pnm = '<span style="color:red;">未设定</span>';
  	        		if(value && value.length>0) {
  	        			pnm = value;
  	        		}
	        		return pnm;
	        	}
		    },
  	        {field:'pay_platform',title:'支付平台',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pf = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: pf="微信"; break;
  	        			case 20: pf="支付宝"; break;
  	        		}
  	        		return pf;
	        	}
		    },
	        {field:'total_fee',title:'订单金额',width:35,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id) return "N/A";
		    		  var show = Number(value||'0')/100;
		    		  return '<span style="color:red;">'+show+'</span>元';
		    	  }
		      },
		    {field:'express_type',title:'运费',width:20,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var mt = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: mt='<span style="color:green">已付</span>'; break;
  	        			case 20: mt='<span style="color:red">到付</span>'; break;
  	        		}
  	        		return mt;
	        	}
		    },
	        {field:'addr_name',title:'收件人',width:30,align:'center',sortable:false},
		    {field:'addr_id',title:'收件地址',width:55,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
	        		return (rowData.addr_city||'') + ' '+ (rowData.addr_detail||'');
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:80,align:'center',sortable:false},
	    ]],
	    hideColumn:['user_type'],
	    pagination : false,
		rownumbers : false
	});
}

/**	重置时间
 * */
function clearTime(){
	$("#queryDateStart").datetimebox('setValue','');
	$("#queryDateEnd").datetimebox('setValue','');
}

function initDetailGrid(){
	$('#detailGrid').datagrid({
	    url:appPath + "/itbOrders/getDetailsInfoPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'thumb',title:'商品缩略图',width:50,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
	        		var itemThumbs = JSON.parse(rowData.item_thumbs||'[]');
	        		if ( itemThumbs && itemThumbs.length>0 && itemThumbs[0].length>0) {
	        			var showImg = itemThumbs[0]+'?x-oss-process=image/resize,m_pad,h_120,w_120,color_cccccc';
	        			retUrl = '<a href="' + itemThumbs[0] + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:60px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="' +showImg+ '" style="display:inline;max-height:60px;max-width:60px"></span>'
	        				+ '</div></a>';
	        		}
	        		return retUrl;
	        	}
	        },
	        {field:'detail_id',title:'明细ID',width:30,align:'left',sortable:false},
	        {field:'detail_no',title:'明细编号',width:40,align:'left',sortable:false},
	        // [明细状态]暂不使用
//	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
//  	        	formatter:function(value, rowData, rowIndex){
//	        		if(!rowData.detail_id) return '<span style="color:red;">N/A</span>';
//	        		var show = getState4Show(value);
//	        		return "<a href='javascript:void(0)' onClick='editState("+rowData.order_id+","+rowData.detail_id+")'>"+show+"</a>";
//	        	}
//		    },
	        {field:'item_id',title:'商品ID',width:30,align:'left',sortable:false },
	        {field:'pp_id',title:'套餐ID',width:30,align:'left',sortable:false },
	        {field:'unit',title:'计量单位',width:30,align:'left',sortable:false },
	        {field:'qty',title:'数量',width:35,align:'left',sortable:false },
	        {field:'fee',title:'金额(分)',width:35,align:'left',sortable:false },
	        {field:'tracking_no',title:'运单号',width:40,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.detail_id) return '<span style="color:red;">N/A</span>';
	        		if (rowData.unit == '月') return 'N/A';
	        		var show = (rowData.express||'')+'['+(value||'NULL')+']';
	        		return "<a href='javascript:void(0)' onClick='editExpress("+rowData.detail_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'user_doc_id',title:'用户作品',width:30,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = value;
	        		if (Number(value||'0')>0) {
	        			var url = getHomeServer()+'/preview/pDocV?docId='+value;
	        			show = '<a href="' + url + '" target="_blank">'+value+'</a>';
	        		}
	        		return show;
	        	}
	        },
	        {field:'user_docEdit',title:'作品编辑',width:30,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<a href="javascript:void(0)" onclick="editUserDoc('+rowData.user_doc_id+')">编辑作品</a>';
	        	}
	        },
	        {field:'create_time',title:'创建时间',width:30,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:30,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	    
	});
}

function editUserDoc(id){
	$.messager.confirm('确定','是否确认修改用户作品？',function(r){
		if(r) {
			var editorUrl = getHomeServer()+"/encrypt/encrypt"+
			urlWithPara(
				{'isDesign':'0',// 字符类型
					'docId':id,
					'typeL':4,
					'isVip':'0',// 字符类型
					'destination':'/web_v6_0_goods/webV6_0/edit.html'
				});
			window.open(editorUrl);
		}
	});
}

function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:blue">待支付</span>'; break;
		case 11: state='<span style="color:green">已支付</span>'; break;
		case 12: state='<span style="color:red">支付失败</span>'; break;
		case 20: state='<span style="color:brown">制作中</span>'; break;
		case 30: state='<span style="color:brown">配送中</span>'; break;
		case 40: state='<span style="color:green">完成</span>'; break;
		case 50: state='<span style="color:red">取消</span>'; break;
	}
	return state;
}

// 状态编辑
function editState(orderId,detailId){
	$("#stateDlg").show();
	$('#stateForm').form('clear');
	$("#updDesc").val('');
	$("#updOrderNo").html('');
	$("#updOrderState").combobox('enable');

	$("#updOrderId").val(orderId);
	$("#updDetailId").val(detailId);
	
	var title = '订单状态';
	var url = appPath + "/itbOrders/getOrdersInfoLst.action?order_id="+ orderId;
	if(Number(detailId||'0')>0){
		title = '订单明细(子订单)状态';
		url = appPath + "/itbOrders/getDetailsInfoLst.action?detail_id="+ detailId;
	}
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updOrderNo").html(info.order_no||info.detail_no||'');
			$("#updOrderState").combobox('select',info.state||0);
			if(info.state==40) {
				$("#updOrderState").combobox('disable');// 已完成的不能改
			}
			$("#updDesc").val(info.desc||'');
			$("#updRecdInfo").val(JSON.stringify(info||{}));
		}
	});
	
	$("#stateBtn").show();
	$('#stateDlg').window({
		title: title,
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#stateDlg').window('move',{top:20,left:20});
	$('#stateDlg').window('open');
}
function cancelUpdState(){
	$('#stateDlg').window('close');
}
function doUpdState(){
	var id = $("#updOrderId").val();
	var did = $("#updDetailId").val();
	var state = Number($("#updOrderState").combobox('getValue')||'0');
	var desc = $("#updDesc").val();
	var recdInfo = JSON.parse($("#updRecdInfo").val()||'{}');
	
	// 默认更新订单
	var url = appPath+"/itbOrdersWeb/updOrder.action";
	var sendData = {
		"orderInfo.order_id": Number(id||"0"),
		"orderInfo.state": state,
		"orderInfo.desc": desc||''
	};
	
	if(Number(did||'0')>0){
		// 更新订单明细
		url = appPath+"/itbOrdersWeb/updDetail.action";
		sendData = {
			"detailInfo.detail_id": Number(did||"0"),
			"detailInfo.state": state,
			"detailInfo.desc": desc||''
		};
	}
	
	$.loading(true);
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			// 添加历史纪录
			var url2 = appPath+"/itbOrdersWeb/addStateHis.action";
			var sendData2 = {
				"stateHisInfo.type": 10,
				"stateHisInfo.trade_obj_id": Number(did||id||"0"),
				"stateHisInfo.total_fee": recdInfo.fee||recdInfo.total_fee||0,
				"stateHisInfo.user_id": recdInfo.user_id||0,
				"stateHisInfo.state": Number(state || "0"),
				"stateHisInfo.desc": desc||''
			};
			$.post(url2, sendData2, function(data2){
				$.loading(false);
				if(data == "ok") {
					$.messager.alert('提示信息','订单状态更新成功','info');
					$('#stateDlg').window('close');
					
					if(Number(did||'0')>0){
						doQuery2();
					} else {
						doQuery();
					}	
				} else {
					$.messager.alert('提示信息','订单状态已更新<br>但[状态历史]添加失败','info');
				}
			});
			
			// 发送[发货]通知
			if(state==30) {
				var url3 = appPath+"/itbOrdersWeb/notifyUser.action";
				var sendData3 = {
					"orderInfo.order_id": Number(id||"0"),
					"orderInfo.user_id": Number(recdInfo.user_id||'0'),
					"orderInfo.state": Number(state || "0")
				};
				$.post(url3, sendData3, function(data3){
					if(data == "ok") {
						$.messager.alert('提示信息','用户通知已发送','info');
					} else {
						$.messager.alert('提示信息','用户通知发送失败','info');
					}
				});
			}
					
        } else {
        	$.loading(false);
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

// 打开订单明细（子订单）窗口
function showDetail(orderId){
	$('#detailForm').form('clear');
	$("#dtlOrderNo").html('');
	$("#dtlOrderId").val(orderId);
	
	var url = appPath + "/itbOrders/getOrdersInfoLst.action?order_id="+ orderId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#dtlOrderNo").html(info.order_no||'');
			$("#dtlUserId").html(info.user_id||'');
		}
	});
	
	doQuery2();
	
	$("#detailBtn").show();
	$('#detailDlg').window({
		title:'订单明细',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#detailDlg').window('move',{top:20,left:20});
	$('#detailDlg').window('open');
}

function closeDetail(){
	$('#detailDlg').window('close');
}

// 删除订单
function delOrder(){
	var selectItem=$("#ordersGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择订单！','warning');
		return;
	}
	for(var i=0; i<selectItem.length; i++){
		var chk = Number(selectItem[i].state||'0');
		if(chk==20||chk==40||chk==50){
			$.messager.alert('提示信息','不能删除当前状态的订单！','warning');
			return;
		}
	}
	$.messager.confirm("确认", "是否确认[删除]所选订单？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.order_id + ",";
				});
				var url = appPath+"/itbOrdersWeb/delOrder.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 导出订单中用户文档信息
function downOdrUserDocInfo(orderId){
	$.messager.confirm('确定','是否确定导出订单中的用户文档数据？',function(r){
		if(r){
			$.loading(true);
			var downUrl = appPath+"/itbOrdersWeb/downOdrUserDocInfo.action";
			$.post(downUrl,{"orderId":(orderId||0)},function(ret){
				$.loading(false);
				if(ret && ret.length>0) {
					$("#exOrder").window('close');
					$("#exOrderGrid").html('');
					var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
					var fNm = "ITB_ODR_USERDOC_INFO_"+strDate+".csv";
					var blob = new Blob([ret]);
					var aLink = $('#downA');
					aLink.html(fNm);
					aLink.attr("download", fNm);
					aLink.attr("href", URL.createObjectURL(blob));
					$("#downBtn").show();
					$('#downDlg').window({
						title:'用户文档信息下载',
						iconCls:'icon-save',
						modal: true,
						shadow: true,
						collapsible:false,
						minimizable:false,
						maximizable:false
					});
					$('#downDlg').window('move',{top:20,left:20});
					$('#downDlg').window('open');
					
				} else {
					$.messager.alert('提示信息','数据获取失败','info');
				}
			});
		}
	});
}

// 导出订单信息
// flg: 1高精度,0普通精度  
// cutBleed: 0带出血,1不带出血 
// 生成印刷稿的接口，加了个参数：cutBleed,表示对出血区域的处理方式，例如 1:裁掉出血,0:带3mm出血,-1:带2mm出血
function downOrderInfo(flg,cutBleed,orderId){
	var ids='';
	if(orderId==0){
		ids = $("#allIds").val();
	}else{
		var selectItem = $("#ordersGrid").datagrid('getChecked');// 选中的订单
		if (!selectItem || selectItem.length == 0){
			return $.messager.alert('提示信息','请勾选需要导出的订单,建议勾选一个!','warning');
		}
		$.each(selectItem,function(index,Item){
			ids = ids + Item.order_id +",";
		});
	}
	
	
	var ret = '<span style="color:red;">未知</span>';
	if (cutBleed == 0 && flg == 0){
		ret = '<span style="color:blue;">普通精度</span><span style="color:green;">(带出3毫米血)</span>';
	} else if(cutBleed == 0 && flg == 1 ) {
		ret = '<span style="color:blue;">高精度</span><span style="color:green;">(带出3毫米血)</span>';
	} else if(cutBleed == 1 && flg == 0){
		ret = '<span style="color:blue;">普通精度</span><span style="color:green;">(不带出血)</span>';
	} else if(cutBleed == 1 && flg == 1){
		ret = '<span style="color:blue;">高精度</span><span style="color:green;">(不带出血)</span>';
	} else if(cutBleed == -1 && flg == 0){
		ret = '<span style="color:blue;">普通精度</span><span style="color:red;">带(2毫米出血)</span>';
	} else if(cutBleed == -1 && flg == 1){
		ret = '<span style="color:blue;">高精度</span><span style="color:red;">带(2毫米出血)</span>';
	} else if(cutBleed == -2 && flg == 0){
		ret = '<span style="color:blue;">普通精度</span><span style="color:red;">带(1毫米出血)</span>';
	} else if(cutBleed == -2 && flg == 1){
		ret = '<span style="color:blue;">高精度</span><span style="color:red;">带(1毫米出血)</span>';
	} else {
		return $.messager.alert('提示信息','参数设置错误！','info');
	}
	
	
	
	
	$.messager.confirm('确定','是否确定导出 '+ret+' 订单？',function(r){
		if(r){
			
			if(ids.length>0){
				ids =ids.substr(0,ids.length-1);//去掉 最后一个逗号
			}
			
			console.log(ids);
			
			if(ids){
				$.loading(true);
			//	var imgUrl = getApiServer()+"/print/createImageForPrint";
				var imgUrl = getApiServer()+"/print/createImageForPrintEx";//一键导出 多个订单
				var param = {
					"device":1,
					"reuse":0,/*重新生成*/
					"orderId":(ids||0),
					"cutBleed":Number(cutBleed,'0')
				}
				console.log(param);
				if(flg==1) {//获取高精度的图片
					param.zoom=2;
				} else {
					param.zoom=1;
				}
				$.post(imgUrl, param, function(ret){// 获取图片地址
						if (ret.success==1){
							var imgLst = ret.data||[];
							var obj = {"orderId":(ids||0),"printImgsInfo":JSON.stringify(imgLst),"withBleed":1,"zoom":param.zoom};
							doExport(obj);
						} else {
							var imgLst = [];
							var obj = {"orderId":(ids||0),"printImgsInfo":JSON.stringify(imgLst),"withBleed":1,"zoom":param.zoom};
							doExport(obj);
						}
				});
			}else{
				$.messager.alert('提示信息','暂无订单可以导出！','info');
			}
		}
	});
}

function doExport(data){
	console.log(data);
	var downUrl = appPath+"/itbOrdersWeb/downOrderInfo.action";
	$.post(downUrl,data,function(ret){
//		$('#downOrdDiv').window('close');
		$.loading(false);
		if(ret && ret.length>0) {
			$("#exOrder").window('close');
			$("#exOrderGrid").html('');
			var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
			var fNm = "ITB_ORDER_INFO_"+strDate+".csv";
			var blob = new Blob([ret]);
			var aLink = $('#downA');
			aLink.html(fNm);
			aLink.attr("download", fNm);
			aLink.attr("href", URL.createObjectURL(blob));
			$("#downBtn").show();
			$('#downDlg').window({
				title:'订单信息下载',
				iconCls:'icon-save',
				modal: true,
				shadow: true,
				collapsible:false,
				minimizable:false,
				maximizable:false
			});
			$('#downDlg').window('move',{top:20,left:20});
			$('#downDlg').window('open');
			
		} else {
			$.messager.alert('提示信息','数据获取失败','info');
		}
	});
}

function cancelDown(){
	$('#downDlg').window('close');
}

// 编辑物流信息
function editExpress(dId){
	$("#expressDlg").show();
	$('#expressForm').form('clear');

	$("#expDetailId").val(dId);
	
	var ex_id = 0;
	var url = appPath + "/itbOrders/getDetailsInfoLst.action?detail_id="+ dId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			if(info.exc_id){
				ex_id = info.exc_id;
			}
			$("#expType").combobox('select',ex_id).combobox('enable');
			$("#expDetailNo").html(info.detail_no||'');
			$("#editExpress").val(info.express||'');
			$("#editTrackNo").val(info.tracking_no||'');
		}
	});
	
	$("#expressBtn").show();
	$('#expressDlg').window({
		title: '订单物流信息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#expressDlg').window('move',{top:20,left:20});
	$('#expressDlg').window('open');
}
function cancelUpdExp(){
	$('#expressDlg').window('close');
}
function doUpdExp(){
	var did = $("#expDetailId").val();
	var express = $("#editExpress").val()||'';
	var trackNo = $("#editTrackNo").val()||'';
	var exc_id = $("#expType").combobox('getValue');//获取快递主键
	if(trackNo){
		var exc_id = $("#expType").combobox('getValue');
		if(exc_id==0){
			return $.messager.alert('提示信息','请选择快递分类！','warning');
		}
	}
	
	// 默认更新订单
	var url = appPath+"/itbOrdersWeb/updDetail.action";
	var	sendData = {
		"detailInfo.detail_id": Number(did||"0"),
		"detailInfo.express": express||'',
		"detailInfo.tracking_no": trackNo||'',
		"detailInfo.exc_id":exc_id || ''
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','更新成功','info');
			$('#expressDlg').window('close');
			doQuery2();			
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

// 合作方
function editPartner(orderId,orderNo,pId) {
	$("#partnerDlg").show();
	$('#partnerForm').form('clear');

	$("#parOrderId").val(orderId);
	$("#parOrderNo").html(orderNo||'');
	$("#updPartner").combobox('select',pId||1);
	
	$("#partnerBtn").show();
	$('#partnerDlg').window({
		title: '合作方设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#partnerDlg').window('move',{top:20,left:20});
	$('#partnerDlg').window('open');
}
function cancelUpdPartner(){
	$('#partnerDlg').window('close');
}
function doUpdPartner(){
	var id = $("#parOrderId").val();
	var pId = $("#updPartner").combobox('getValue');
	
	var url = appPath+"/itbOrdersWeb/updOrder.action";
	var sendData = {
		"orderInfo.order_id": Number(id||"0"),
		"orderInfo.partner_id": Number(pId || "0"),
	};
	
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			$.messager.alert('提示信息','更新成功','info');
			$('#partnerDlg').window('close');
			doQuery();
					
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

/**
 * 获取请求信息(订单列表)
 */
function getQueryParam(){
	var queryObject = {};
	
	var findType = $("#queryType").combobox('getValue');
	var findState = $("#queryState").combobox('getValue');
	var findPartner = $("#queryPartner").combobox('getValue');
	var findPay= $("#queryPayPf").combobox('getValue');
	var findOrderId = $("#queryOrderId").val();
	var findNo = $("#queryOrderNo").val();
	var findPayNo = $("#queryPayOrderNo").val();
	var findInvId = $("#queryInvId").val();
	var findMobile = $("#queryMobile").val();
	
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findUserId = $("#queryUserId").val();// 用户ID
	if (Number(findUserId)>0) queryObject.findUserId = findUserId;// 查找用户
	
	if(findType && findType.length>0) queryObject.findType = findType;// 分类
	if(findState && Number(findState||'0')>0) queryObject.findState = findState;// 状态
	if(findOrderId && Number(findOrderId||'0')>0) queryObject.findOrderId = findOrderId;// 订单id
	if(findNo && findNo.length>0) queryObject.findOrderNo = findNo;// 订单号
	if(findPayNo && findPayNo.length>0) queryObject.findPayOrderNo = findPayNo;// 支付订单号
	if(findPartner && Number(findPartner||'0')>0) queryObject.findPartner = findPartner;// 合作方
	if(findPay && Number(findPay||'0')>0) queryObject.findPayPf = findPay;// 支付平台
	if(findInvId && Number(findInvId||'0')>0) queryObject.findInvId = findInvId;// 发票id
	if(findMobile && Number(findMobile||'0')>0) queryObject.findMobile = findMobile;// 手机号

	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS+' 00:00:00';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59';
	
	return queryObject;
}

/**
 * 获取请求信息(订单详细列表)
 */
function getQueryParam2(){
	var queryObject = {
		findPubFlg: 1,
		findOrderId: Number($("#dtlOrderId").val()||'0')
	};
	return queryObject;
}

/**一键导出数据
 * */
function exportAlls(){
	var par=$("#queryPartner").combobox('getValue');
	if(par && par>0){
		var startDate = $("#queryDateStart").datetimebox('getValue');
		var endDate = $("#queryDateEnd").datetimebox('getValue');
		if(startDate && startDate.length>0 && endDate && endDate.length>0){
			// 合作方(检索用)
			$("#exPartner").combobox({disabled:true});
			$("#exPartner").combobox({
				url:appPath+'/itbOrders/getPartnerForCombo.action?blkFlg=1',
				valueField:'id',
				textField:'name',
				value:par
			});
			$("#exStartDate").val(startDate);
			$("#exStartDate").attr('readonly',true);
			$("#exEndDate").val(endDate);
			$("#exEndDate").attr('readonly',true);
			$("#exOrderBtn").show('slow');
			$('#exOrder').window({
				title: '一键生成订单详情',
				iconCls:'icon-edit',
				modal: true,
				shadow: false,
				collapsible:false,
				minimizable:false,
				maximizable:false
			});
			initExOrderGrid();
			$('#exOrder').window('move',{top:20,left:20});
			$('#exOrder').window('open');
		}else{
			$.messager.alert('提示信息','请选择需要导出的订单所在时间区间！','info');
		}
	}else{
		$.messager.alert('提示信息','必须选择一个合作方！','info');
	}
}


/**	取消	导出所有 订单
 **/
function cancleDown(){
	$("#exOrder").window('close');
	$("#exOrderGrid").html('');
}

/** 查询数据
 */
function doQuery(startFlg){
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	if(findDtS && findDtS.length>0){
		var sDate=chkInputDate(findDtS);
		$("#queryDateStart").datetimebox('setValue',sDate);
	}
	if(findDtE && findDtE.length>0){
		var eDate=chkInputDate(findDtE);
		$("#queryDateEnd").datetimebox('setValue',eDate);
	}
	
	$("#ordersGrid").datagrid('unselectAll');
	if(startFlg==1){
		$("#ordersGrid").datagrid('load', getQueryParam());
	} else {
		$("#ordersGrid").datagrid('reload', getQueryParam());
	}
}
function doQuery2(){
	$("#detailGrid").datagrid('unselectAll');
	$("#detailGrid").datagrid('load', getQueryParam2());
}

// 判断日期格式[YYYY-MM-DD]
function chkInputDate(str){
	var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;  
	var r = str.match(reg); 
	if(r==null)return '';  
	r[2]=r[2]-1;  
	var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);  
	if(d.getFullYear()!=r[1])return '';  
	if(d.getMonth()!=r[2])return '';  
	if(d.getDate()!=r[3])return '';  
	if(d.getHours()!=r[4])return '';  
	if(d.getMinutes()!=r[5])return '';  
	if(d.getSeconds()!=r[6])return '';  
	return str;  
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

// 指定优惠券
function initCoupon(){
	$('#couponGrid').datagrid({
	    url:appPath + "/itbCoupon/getCouponInfoPg.action?findYhUse=40",// 40指定发放优惠券
	    height:'360',
	    striped:true,
	    fitColumns:true,
	    queryParams: getCouponParm(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
  	        {field:'c_id',title:'券ID',width:30,align:'center',sortable:false},
  	        {field:'lot_no',title:'批次号',width:50,align:'center',sortable:false},
	        {field:'c_code',title:'优惠码',width:60,align:'center',sortable:false},
  	        {field:'type',title:'券类型',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.c_id) return "N/A";
	        		return getState4Show(value);
	        	}
		    },
	        {field:'discount',title:'优惠额(￥)',width:30,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return Number(value||'0')/100 + ' 元';
	        	}
	        },
	        {field:'org_id',title:'持有组织',width:40,align:'left',sortable:false},
	        {field:'owner',title:'持有者',width:40,align:'left',sortable:false},
	        {field:'channel_u',title:'营销者',width:35,align:'left',sortable:false},
	        {field:'min_order_fee',title:'Min订单金额',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return Number(value||'0')/100 + ' 元';
	        	}
	        },
  	        {field:'issue_time',title:'发放时间',width:60,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return value.substr(0,10);
	        	}
	        },
	        {field:'expiry_time',title:'有效截止日',width:60,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(value && value.length>0) {
	        			return value.substr(0,10);
	        		}
	        		return '<span style="color:green">不限</span>';
	        	}
	        },
	        {field:'limit_type',title:'限制范围',width:40,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = '<span style="color:green">不限</span>';
	        		switch(Number(value||'0')){
	        			case 1: show='<span style="color:red">海报模版</span>'; break;
	        			case 2: show='<span style="color:red">多页模版</span>'; break;
	        			case 3: show='<span style="color:red">PPT模版</span>'; break;
	        			case 4: show='<span style="color:red">印品</span>'; break;
	        			case 5: show='<span style="color:red">配件</span>'; break;
	        			case 6: show='<span style="color:red">社交媒体</span>'; break;
	        			case 7: show='<span style="color:red">电商</span>'; break;
	        			case 8: show='<span style="color:red">微商</span>'; break;
	        			case 9: show='<span style="color:red">虚拟商品</span>'; break;
	        			case 1010: show='<span style="color:red">Logo商品</span>'; break;
	        		}
	        		return show;
	        	}
	        },
	        {field:'use',title:'用途',width:35,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = '<span style="color:red">未知</span>';
	        		switch(Number(value||'0')){
	        			case 10: show='<span style="color:green">通用</span>'; break;
	        			case 20: show='<span style="color:orange">APP抽奖[印品]</span>'; break;
	        			case 30: show='<span style="color:blue">合伙人抽奖[印品]</span>'; break;
	        			case 31: show='<span style="color:red">合伙人抽奖[会员充值]</span>'; break;
	        			case 40: {
	        				show='<span style="color:red">指定发放</span>';
	        				if(Number(rowData.state||'0')==10) {
	        					show = '<a href="javascript:void(0)" onclick="showGrantDlg('+rowData.c_id+')">去发放</a>';
	        				}
	        			}
	        			break;
	        		}
	        		return show;
	        	}
	        },
	        {field:'desc',title:'备注',width:60,align:'left',sortable:false},
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = '<span style="color:red">未知</span>';
	        		switch(Number(value||'0')){
	        			case 10: show='<span style="color:green">未兑换</span>'; break;
	        			case 15: show='<span style="color:blue">已领取</span>'; break;
	        			case 20: show='<span style="color:blue">已兑换</span>'; break;
	        			case 30: show='<span style="color:blue">已下单</span>'; break;
	        			case 40: show='<span style="color:red">已使用</span>'; break;
	        		}
	        		return show;
	        	}
	        },
	        {field:'mobile',title:'手机号',width:30,align:'center',sortable:false},
	        {field:'user_id',title:'兑换人',width:45,align:'center',sortable:false},
  	        {field:'used_time',title:'使用时间',width:60,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(value && value.length>0) {
	        			return "<span style='color:red;'>"+value+"</span>";
	        		}
	        		return "<span style='color:green;'>未使用</span>";
	        	}
	        },
	        {field:'trade_obj_id',title:'订单ID',width:35,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}	        
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true
	});
}

//指定发放
function showGrantDlg(cId){
	$("#grantTable").show();
	$('#grantForm').form('clear');
	var userId = $('#hiCouponUserId').val();
	$("#grantSpanUserId").html(userId);
	$("#grantUserId").val(userId);
	
	$("#grantCId").val(cId||0);
	
	// 加载数据
	var url = appPath + "/itbCoupon/getCouponInfoLst.action?c_id="+cId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#grantCCd").html(info.c_code||'');
			$("#grantExpiryTime").datebox('setValue', (info.expiry_time||'').substr(0,10));
			$("#grantDesc").val(info.desc||'');
		}
	});
	$("#grantBtn").show();
	$('#grantDlg').window({
		title:'给指定用户发放优惠券面板',
		iconCls:'icon-reload',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#grantDlg').window('move',{top:150,left:350});
	$('#grantDlg').window('open');
}

//发放给指定用户
function doGrant(){
	var gCId = $("#grantCId").val();
	var gUId = $("#grantUserId").val();
	var gExpiryTime = $('#grantExpiryTime').datebox('getValue');//有效截止时间
	var gDesc = $("#grantDesc").val();//备注
	if(Number(gCId||'0')>0
		&& Number(gUId||'0')>0
		&& gExpiryTime && gExpiryTime.length>0
		&& gDesc && gDesc.length>0) {
		
		// 确认
		$.messager.confirm("确认", "是否确认发放该优惠券？</br><font color='red'>发放后无法修改!是否Go on?</font>",
			function(r){
		        if (r) { 
		        	var url = appPath+"/itbCouponWeb/grantCoupon.action";
		    		$.loading(true);
		    		var sendData = {
		    			"couponInfo.c_id": Number(gCId || '0'),
		    			"couponInfo.user_id": Number(gUId || '0'),
		    			"couponInfo.expiry_time": gExpiryTime+' 23:59:59',
		    			"couponInfo.desc": gDesc||'',
		    		};
		    	    $.post(url, sendData, function(data){
		    	    	$.loading(false);
		    			if (data == "ok") { 
		    				$.messager.alert('提示信息','发放成功','info');
		    				$('#grantDlg').window('close');
		    				queryCoupon();
		    	        } else {
		    	        	$.messager.alert('提示信息','发放失败','info');
		    	        }
		    	    });
		        }
			}
		);
		
	} else {
		$.messager.alert('提示信息','请填写完整信息','info');
	}
}

function cancelGrant(){
	$('#grantDlg').window('close');
}

/**
 * 获取请求信息
 */
function getCouponParm(){
	var queryObject = {};
	
	var findCode = $("#queryYhCode").val();
//	var findType = $("#queryYhType").combobox('getValue');
	var findUserId = $("#queryConverUserId").val();// 兑换人用户
	var findState = $("#queryYhState").combobox('getValue');
	var findLimit = $("#queryYhLimit").combobox('getValue');
	
	var findExpiryDtS = $("#queryExpiryDateStart").datebox('getValue');
	var findExpiryDtE = $("#queryExpiryDateEnd").datebox('getValue');
	
	
//	if(findType && Number(findType||'0')>0) queryObject.findYhType = findType;// 优惠券类型
	if(findState && Number(findState||'0')>0) queryObject.findYhState = findState;// 状态
	if(findLimit && Number(findLimit||'0')>0) queryObject.findYhLimit = findLimit;// 限制
	if(findCode && findCode.length>0) queryObject.findYhCode = findCode;// 优惠券码
	if (Number(findUserId)>0) queryObject.findConverUserId = findUserId;// 兑换人用户ID
	
	if(findExpiryDtS && findExpiryDtS.length>0) queryObject.findExpDateStart = findExpiryDtS+' 00:00:00';//	有效截止时间[开始]
	if(findExpiryDtE && findExpiryDtE.length>0) queryObject.findExpDateEnd = findExpiryDtE+' 23:59:59';//	有效截止时间[结束]
	
	return queryObject;
}

/**
 * 查询数据
 */
function queryCoupon(){
	$("#couponGrid").datagrid('unselectAll');
	$("#couponGrid").datagrid('load', getCouponParm());
}